#include "WebSync.h"

extern "C" {
#include <oauth.h>
}

DoubanSync::DoubanSync()
{

}

DoubanSync::~DoubanSync()
{

}

BPcode DoubanSync::RequestToken()
{
    int fail=0;

    const char *url= "http://www.douban.com/service/auth/request_token";
			 //< the url to sign
    const char *c_key= "05f9b747a1d4c72611ed25d6e57e5572";
			//< consumer key
    const char *c_secret = "214d3c553c931442";
			//< consumer secret

    const char *t_key= "0987654321fedcba0987654321fedcba098765432";
			//< token key
    const char *t_secret = "66666666666666666666666666666666";
			//< token secret*/

    char *res_t_key= NULL; //< replied key
    char *res_t_secret = NULL; //< replied secret

    char *req_url = NULL;
    char *reply;

    req_url = oauth_sign_url2(url, NULL, OA_HMAC, NULL, c_key, c_secret, NULL, NULL);
    bplog(LOG_LEVEL_INFO,"GET: URL:%s", req_url);

    reply = oauth_http_get(req_url,NULL);
    if(!reply)
        bplog(LOG_LEVEL_INFO,"DoubanSync:HTTP request for an oauth request-token failed.");
    else
    {
        int rc;
        char **rv = NULL;

        bplog(LOG_LEVEL_INFO,"HTTP-reply: %s", reply);
        rc = oauth_split_url_parameters(reply, &rv);
        qsort(rv, rc, sizeof(char *), oauth_cmpstringp);
        if(rc==2
            && !strncmp(rv[0],"oauth_token=",11)
            && !strncmp(rv[1],"oauth_token_secret=",18))
            {
                res_t_key=strdup(&(rv[0][12]));
                res_t_secret=strdup(&(rv[1][19]));
                bplog(LOG_LEVEL_INFO,"DoubanSync:key:'%s' secret: '%s'",res_t_key, res_t_secret);
            }

        if(rv)
            free(rv);
    }

    if(req_url) free(req_url);
    if(reply) free(reply);
    if(res_t_key) free(res_t_key);
    if(res_t_secret) free(res_t_secret);

    return BP_OK;
}
